<template>
    <div class="right-body">
        <div class="right-top public-bg">
            <div class="public-title">预警统计</div>
            <div class="title-nav" id="chart1"></div>
        </div>
        <div class="right-con public-bg">
            <div class="public-title">桥隧预警信息</div>
                <div class="title-nav">
                    <ul class="list1">
                        <li class="li1">
                        <p>现在时间</p>
                        <p>设备ID</p>
                        <p>设备类型</p>
                    </li>
                    </ul>
                    <ul class="list">
                    <vue3-seamless-scroll :list="data2" class="warp" :step="0.6" :visibleCount="data2.length">
                    <li v-for="(item, index) in data2" :key="index" class="li2">
                        <p>{{ item.time }}</p>
                        <p>{{ item.parentGatewayId }}</p>
                        <p>{{ item.name }}</p>
                    </li>
                   </vue3-seamless-scroll> 
                </ul>
                
               
                </div>
        </div>
        <div class="right-bottom public-bg">
            <div class="public-title">桥隧健康状况</div>
            <div class="title-nav" id="chart2"></div>
        </div>
    </div>
</template>

<script>
import { ElNotification } from 'element-plus'
import {Vue3SeamlessScroll} from 'vue3-seamless-scroll'
import * as echarts from 'echarts';
import axios from 'axios';
export default {
    name: 'RightPart',
    props: {
        // 中心坐标
        center: {
            type: Object,
            default: () => ({ lng: 116.404, lat: 39.915 })
        },
        // 缩放级别
        zoom: {
            type: Number,
            default: 15
        }
    },
    components: {
        Vue3SeamlessScroll
    },
    data() {
        return {
            down:"down",
            count: 0,
            service: "",
            token: "",
            data: [],
            data2: [
                {
                    id: '',
                    name: '倾角传感器',
                    parentGatewayId: 'ZRZY342300001',
                    time: new Date().toLocaleString()
                },
                {
                    id: '',
                    name: '倾角传感器',
                    parentGatewayId: 'ZRZY342300001',
                    time: new Date(Date.now() - 1000).toLocaleString()
                },
                {
                    id: '',
                    name: '倾角传感器',
                    parentGatewayId: 'ZRZY342300001',
                    time: new Date(Date.now() - 2000).toLocaleString()
                },
                
            ],

            warningCount: 62, // 添加预警计数器
            timer: null, // 添加定时器引用
            lastParentGatewayId: '', // 添加变量跟踪上一次的parentGatewayId
        }
    },
    mounted() {
        this.timer = setInterval(() => {
            //
            axios.get('/api/jetlinks/device-instance/ZRZY342300001-ANGLE/logs', {
                headers: {
                    //携带token
                    'X-Access-Token': this.token
                }
            })
                .then((response) => {
                    this.data = response.data.result.data

                    if (this.data.length > 0) {
                        //取出data数组前三个数据
                        this.data = this.data.slice(0, 3);
                        
                        //创建新的data2数组来确保响应式更新
                        const newData2 = [];

                        //循环遍历data数组，实现取出content字段转json
                        for (let i = 0; i < this.data.length; i++) {
                            this.data[i] = JSON.parse(this.data[i].content);
                            console.log(this.data[i]);

                            // 为每个设备生成稍微不同的时间（模拟不同设备的数据时间）
                            const baseTime = new Date();
                            const deviceTime = new Date(baseTime.getTime() - (i * 1000)); // 每个设备时间相差1秒

                            newData2.push({
                                id: this.data[i].headers._uid || '',
                                name: this.data[i].headers.deviceName || '',
                                parentGatewayId: this.data[i].headers.parentGatewayId || '',
                                time: deviceTime.toLocaleString(),
                                properties: this.data[i].properties
                            });
                        }

                        // 检查id是否发生变化
                        if (newData2.length > 0 && newData2[0].id !== this.lastParentGatewayId) {
                            // 只有当id发生变化时才触发通知和计数器增加
                            ElNotification({
                                title: '桥梁预警',
                                dangerouslyUseHTMLString: true,
                                message: `
                                <div>${newData2[0].time}</div>
                                <div>设备ID: ${newData2[0].parentGatewayId}</div>
                                <div>X: ${newData2[0].properties.X} &nbsp;&nbsp;&nbsp; Y: ${newData2[0].properties.Y} &nbsp;&nbsp;&nbsp; Z: ${newData2[0].properties.Z}</div> `,
                                type: 'error',
                                duration: 4000
                            });
                            console.log(1);
                            
                            this.warningCount += 1;

                            // 更新lastParentGatewayId（实际存储的是id）
                            this.lastParentGatewayId = newData2[0].id;

                            // 只有当id发生变化时才更新显示
                            this.data2 = [...newData2];
                        }
                    }
                    // 重新设置图表数据
                    this.setChart1();
                }).catch((error) => {
                    console.log("error: ", error);
                });
        }, 2000)
        // 添加预警数值增加定时器

        this.setChart1();
        this.setChart2();
        this.onLogin();

    },

    beforeUnmount() {
        // 清除定时器，防止内存泄漏
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    },

    methods: {

        // },
        async onLogin() {
            // axios.post('http://10.196.61.111:81/jetlinks/authorize/login', {
            axios.post('/api/jetlinks/authorize/login', {
                "username": "admin",
                "password": "admin",
                "expires": 3600000,
                "tokenType": "default",
                "verifyCode": "",
                "verifyKey": ""
            }).then((response) => {
                this.token = response.data.result.token;
                // console.log("response: ", response)
            }).catch((error) => {
                console.log("error: ", error);
            });
        },
        setChart1() {
            let chart1 = echarts.init(document.getElementById('chart1'));
            chart1.setOption({
                tooltip: {
                    trigger: 'item',
                    show: false
                },
                color: ['rgb(80, 112, 221)', 'rgb(226, 189, 94)'],
                legend: {
                    right: '5%',
                    top: '10%',
                    orient: 'vertical',
                    data: ['已处理', '未处理'],
                    textStyle: {
                        color: 'rgb(135, 183, 215)'
                    }
                },
                series: [
                    {
                        name: 'Access From',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        // emphasis: {
                        //     label: {
                        //         show: false,
                        //         fontSize: 40,
                        //         fontWeight: 'bold'
                        //     }
                        // },
                        label: {
                            show: true,
                            position: 'center',
                            formatter: () => `${this.warningCount} \n预警总数`, // 使用动态数据
                            fontSize: 16,
                            fontWeight: 'bold',
                            color: 'rgb(42, 164, 241)'
                        },
                        data: [
                            { value: 59, name: '已处理' },
                            { value: 3, name: '未处理' },
                        ]
                    }
                ]
            });
        },
        setChart2() {
            let chart2 = echarts.init(document.getElementById('chart2'));
            chart2.setOption({
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    bottom: '10%',
                    data: ['a桥', 'b桥', 'a隧道', 'b隧道', 'c隧道'],

                },
                grid: {
                    left: '5%',
                    right: '12%',
                    top: '10%',
                    bottom: '20%',
                    containLabel: true
                },
                radar: {
                    radius: '40%'
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: ['2018', '2019', '2020', '2021', '2022', '2023', '2024']
                },
                yAxis: {
                    type: 'value',

                    scale: true
                },

                series: [
                    {
                        name: 'a桥',
                        type: 'line',
                        data: [800, 300, 500, 700, 630, 680, 750],
                        label: {
                            show: true,
                            // 只在最后一个数据点显示名称
                            formatter: function (params) {
                                // 数据点索引为6时（最后一项）显示名称
                                return params.dataIndex === 6 ? params.seriesName : '';
                            },
                            position: 'right', // 显示在最后一个点右侧
                            color: 'rgb(75, 115, 185)',
                            fontSize: 12
                        },
                    },
                    {
                        name: 'b桥',
                        type: 'line',
                        data: [790, 400, 460, 320, 520, 700, 710],
                        label: {
                            show: true,
                            formatter: function (params) {
                                return params.dataIndex === 6 ? params.seriesName : '';
                            },
                            position: 'right',
                            color: 'rgb(75, 115, 185)',
                            fontSize: 12
                        },
                    },
                    {
                        name: 'a隧道',
                        type: 'line',
                        data: [700, 680, 350, 530, 660, 680, 540],
                        label: {
                            show: true,
                            formatter: function (params) {
                                return params.dataIndex === 6 ? params.seriesName : '';
                            },
                            position: 'right',
                            color: 'rgb(75, 115, 185)',
                            fontSize: 12
                        },
                    },
                    {
                        name: 'b隧道',
                        type: 'line',
                        data: [750, 620, 550, 430, 580, 630, 600],
                        label: {
                            show: true,
                            formatter: function (params) {
                                return params.dataIndex === 6 ? params.seriesName : '';
                            },
                            position: 'right',
                            color: 'rgb(75, 115, 185)',
                            fontSize: 12
                        },
                    },
                    {
                        name: 'c隧道',
                        type: 'line',
                        data: [850, 500, 680, 720, 569, 490, 380],
                        label: {
                            show: true,
                            formatter: function (params) {
                                return params.dataIndex === 6 ? params.seriesName : '';
                            },
                            position: 'right',
                            color: 'rgb(75, 115, 185)',
                            fontSize: 12
                        },
                    }
                ]
            });
        }
    },
}
</script>

<style scoped>
.right-body {
    width: 22%;
    height: 100%;
    float: right;
    margin: 0 0.3%;
}

.right-body .right-top {
    width: 100%;
    height: 32%;
}

.title-nav .top5-ul {
    width: calc(100% - 20px);
    height: calc(100% - 30px);
    padding: 10px;
}

.title-nav .top5-ul ul {
    width: 100%;
    height: 100%;
}

.title-nav .top5-ul ul,
li {
    list-style: none;
}

.title-nav .top5-ul ul>li {
    width: 100%;
    height: 20%;
    color: #ffffff;
    line-height: 68px;
    justify-content: center;
}

.title-nav .top5-ul ul li span {
    margin-left: 3%;
    font-size: 14px;
}

.title-nav .top5-ul ul li span:nth-child(1) {
    color: #EB6841;
    font-style: oblique;
    /*width: 10%;*/
    /*#20a8fe
            #EB6841
            #3FB8AF
            #FE4365
            #FC9D9A*/
    display: inline-block;
    text-align: center;
    font-size: 20px;
}

.title-nav .top5-ul ul li span:nth-child(2) {
    width: 10%;
    display: inline-block;
    text-align: center;

    height: 30px;
    line-height: 30px;
    /*    height: 100%;*/
    /*line-height: 100%;*/
    vertical-align: center;
    border-radius: 5px;
    color: #ffffff;
}

.title-nav .top5-ul ul li:nth-child(1) span:nth-child(2),
.title-nav .top5-ul ul li:nth-child(2) span:nth-child(2),
.title-nav .top5-ul ul li:nth-child(3) span:nth-child(2) {
    background: #d89346;
}

.title-nav .top5-ul ul li:nth-child(4) span:nth-child(2),
.title-nav .top5-ul ul li:nth-child(5) span:nth-child(2) {
    background: #1db5ea;
}

.title-nav .top5-ul ul li span:nth-child(3) {
    /*width: 15%;*/
    display: inline-block;
    text-align: center;
}

.title-nav .top5-ul ul li span:nth-child(4) {
    /*width: 15%;*/
    display: inline-block;
    text-align: center;
}

.title-nav .top5-ul ul li span:nth-child(5) {
    /*width: 20%;*/
    display: inline-block;
    text-align: center;
}

.title-nav .top5-ul ul li span:nth-child(6) {
    display: inline-block;
    text-align: center;
}

.right-body .right-con {
    width: 100%;
    height: 25%;
    margin-top: 2%;
    /* display: flex; */
    overflow: hidden;
    /* border: 1px solid red; */
}

.right-body .right-bottom {
    width: 100%;
    height: 39%;
    margin-top: 2%;
}

.list {
    width: 320px;
    height: 200px;
    margin-left: 15px;
    /* border: 1px solid red; */
}

.list li {
    width: 97%;
    height: 30px;
    display: flex;
    justify-content: space-between;
    /* border: 1px solid red; */
}
.list .li2 p {
    color: #fff;
    font-size: 11px;
}
.list1{
    width: 300px;
    height: 50px;
    margin-left: 25px;
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}
.list1 li{
   width: 100%;
    height: 30px;
    display: flex;
    justify-content: space-between;
}
.list1 .li1 p {
    color: #fff;
}

</style>